//
//  BKPhoneCardsViewController.m
//  bestkeep
//
//  Created by yons on 16/11/25.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKPhoneCardsViewController.h"
#import "BKPhone_NumberView.h"
#import "BKPhone_MainView.h"
#import "BKPhoneCardsRecordViewController.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import <AlipaySDK/AlipaySDK.h>
#import "BKPhonePayView.h"
#import "BKFilterTableViewCell.h"
#import "BKODAliManager.h"
#import "BKPhonePaySkipVC.h"
#import "CacheData.h"
#import "BKIntegralBookViewController.h"
#import "BKPhone_Header.h"
#import "Mediator+BKGD.h"
#import "Mediator+BKClassify.h"
#import "BKPhoneNumberSave.h"
#import "CacheData.h"

typedef void (^BKPhonePayCallback) (id obj, NSError *error);

@interface BKPhoneCardsViewController ()<GetPhoneCardsDataDelegate,AddContactPeopleDelagate,ABPeoplePickerNavigationControllerDelegate,ABPersonViewControllerDelegate, PhonePayViewDelegate, UITableViewDelegate, UITableViewDataSource,WXApiManagerDelegate, BKODAliManagerDelegate, PhoneNumberTextFiledDelegate, BKPhone_headerDelegate>

@property(nonatomic,strong)BKPhone_Header *headerView;
@property(nonatomic,strong)BKPhone_NumberView *numberView;
@property(nonatomic,strong)BKPhone_MainView *mainView;

@property(nonatomic,strong)NSMutableArray *arr;
@property (nonatomic, strong) NSMutableDictionary *payInfo;
@property(nonatomic,strong)NSString *registerNumber;
@property(nonatomic,strong)NSString *phoneNumber;
@property(nonatomic,strong)NSString *phoneName;
@property(nonatomic,strong)NSString *phoneInfo;
@property(nonatomic,strong)NSString *mobileName;
@property (nonatomic, strong) NSString *lastTrueNumber;

@property (nonatomic, strong) UITableView *filterTableView;
@property (nonatomic, strong) NSMutableArray *filterMuArray;
@property (nonatomic, strong) NSMutableArray *addressBookMuArray;
@property (nonatomic, strong) NSMutableArray *tempFilterArray; //用于存储查找的的数组
@property (nonatomic, strong) NSMutableArray *recordsNumberArray;

@property(nonatomic,strong)UIButton *phoneCardsRecordButton;
@property (nonatomic, strong) Complete com;
@property (nonatomic, strong) NSString *isDefineRequestType;
@property (nonatomic, strong) OrderAlipayInfo *alipayInfo;
@property (nonatomic, strong) BKPhonePayView *payView;

//@property(nonatomic,strong) RLMResults<BKPhoneContactInfo*> *phoneContactInfoResults;
//@property(nonatomic,strong)RLMResults<Person*>*personResults;
@property(nonatomic,strong)Person *person;
@property(nonatomic,strong)BKPhoneContactInfo *contactInfo;
@property (nonatomic, strong) ExceptionView *exceptionView;

@end

@implementation BKPhoneCardsViewController


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_payView removeFromSuperview];
    _payView = nil;
    _payView.delegate = nil;
    [HUD dismiss];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self dynamicLayoutView];
    [self requestData];
}

- (void)dynamicLayoutView {
    
    self.title = BKMainLocalizedString(@"BKPhoneCardsTitle");
    [self.view addSubview:self.numberView];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.mainView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.numberView.mas_bottom);
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
        make.bottom.mas_equalTo(self.phoneCardsRecordButton.mas_top).offset(10);
    }];
    self.numberView.delegate = self;
    self.numberView.PhoneNumberdelegate = self;
    self.isDefineRequestType = @"tariffe";
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"BKIntegral_wenhaoicon-"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(explainQuestion)];
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    spaceItem.width = -ApplicationNavigationBarBackGauge;
    self.navigationItem.rightBarButtonItems = @[spaceItem, rightBar];
    
    //添加按钮到BarButton
    UIButton *Button = [UIButton buttonWithType:UIButtonTypeCustom];
    [Button addTarget:self action:@selector(explainQuestion) forControlEvents:UIControlEventTouchDown];
}


#pragma mark ---- 数据请求
//进入页面请求banner和手机号码
-(void)requestData{
    
    NSString *idStr = [NSString stringWithFormat:@"userId = '%@'",[BKMainCommon getUserId]];
    RLMResults *personResults = [[CacheData shareInstance] search:[Person class] predicate:idStr];
    _person = [personResults firstObject];
    
    
    RLMResults *infoResults = [[CacheData shareInstance]search:[BKPhoneContactInfo class] predicate:idStr sorted:BKPhoneContactLocalCreateDateName ascending:NO];
    _contactInfo = [infoResults firstObject];

    if ([BKMainCommon checkNetWork]) {
        [HUD showProgress:nil];
        [BKMainCommon getBKPhoneCardsBannerData:^(id obj, NSError *error) {
            if (obj != nil) {
                
                NSArray *arr = obj[@"bannerInfo"];
                if (arr.count != 0) {
                    [self setBannerWithImageArr:arr];
                }
                self.registerNumber = obj[@"bindMobile"];
                [self setNumberViewUI];

            }else {
                [self setNumberViewUI];
            }
            [HUD dismiss];
        }];


    } else {
        [HUD showErrorMessage: @"请检查您的网络"];
        [self noNetworkCreatDataInfo:^(id obj, NSError *error) {
            self.mainView.isSuccessTariffe = NO;
            self.mainView.phoneCardsTariffeList = obj;
            [self.mainView.tariffeCollectionView reloadData];
        } isFlow:NO];

    }
}
-(void)setBannerWithImageArr:(NSArray *)arr{
    
    self.numberView.frame = CGRectMake(0, 134, ScreenWidth, 100);
    [self.mainView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.numberView.mas_bottom);
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
        make.bottom.mas_equalTo(self.phoneCardsRecordButton.mas_top).offset(10);
    }];
    [self.view addSubview:self.headerView];
    self.headerView.bkPhone_headerDelegate = self;
    
    [self.headerView setImageViewWith:arr];
}

-(void)setNumberViewUI{
    
    if (_person.phones.count > 0) {
        
        self.lastTrueNumber = _contactInfo.phoneNumber;
        self.numberView.phoneTextField.text = [self.numberView formattingPhoneNumber:_contactInfo.phoneNumber];
        self.numberView.QCellCoreLabel.textColor = RGB(152, 152, 152);
        self.numberView.QCellCoreLabel.text = _contactInfo.phoneName;
        self.phoneNumber = _contactInfo.phoneNumber;
        self.phoneName = _contactInfo.phoneName;
        [self requestgetMobileShelfInfosWithPhoneNumber:_contactInfo.phoneNumber];
    }else{
        [self requestgetMobileShelfInfosWithPhoneNumber:self.registerNumber];
        self.phoneNumber = self.registerNumber;
        self.numberView.phoneTextField.text = [self.numberView formattingPhoneNumber:self.phoneNumber];
        self.numberView.QCellCoreLabel.text = self.phoneInfo;
    }
}

//根据号码请求话费数据
-(void)requestgetMobileShelfInfosWithPhoneNumber:(NSString *)str{
    str = [self phoneNumberReplace:str];
    if ([self phoneNumberIsErrorWithNumber:str isFlow:NO]) {
        
    [BKMainCommon getPhoneSelectInfo:^(id obj, NSError *error) {
        if (obj != nil) {
            self.mainView.phoneCardsTariffeList = (BKPhoneCardsList *)obj;
            [self mobileNameFromData:self.mainView.phoneCardsTariffeList.provinceName];
            self.mainView.isSuccessTariffe = YES;
            [self.mainView.tariffeCollectionView reloadData];
        } else {
            [self noNetworkCreatDataInfo:^(id obj, NSError *error) {
                self.mainView.isSuccessTariffe = NO;
                self.mainView.phoneCardsTariffeList = obj;
                [self.mainView.tariffeCollectionView reloadData];
            } isFlow:NO];

        }
    } account_no:str];
        self.lastTrueNumber = str;
    }
}

//根据号码请求流量数据
-(void)requestgetTraficShelfInfosWithPhoneNumber:(NSString *)str{
    str = [self phoneNumberReplace:str];
    if ([self phoneNumberIsErrorWithNumber:str isFlow:YES]) {
    [BKMainCommon getPhoneFlowInfo:^(id obj, NSError *error) {
        if (obj != nil) {
            self.mainView.phoneCardsFlowList = (BKPhoneCardsList *)obj;
            [self mobileNameFromData:self.mainView.phoneCardsFlowList.provinceName];
            self.mainView.isSuccessFlow = YES;
            [self.mainView.flowCollectionView reloadData];
        } else {
            [self noNetworkCreatDataInfo:^(id obj, NSError *error) {
                self.mainView.isSuccessFlow = NO;
                self.mainView.phoneCardsFlowList = obj;
                [self.mainView.flowCollectionView reloadData];
            } isFlow:YES];
        }
    } account_no:str];
    }
}

#pragma mark - 顶部广告栏代理方法回调
- (void)BKPhone_headerPushVC:(NSInteger)integer {
    
    NSDictionary *dic = [self.headerView.codeArr objectAtIndex:integer];
    [self clickGoodsInfoType:[dic[@"type"] integerValue]goodsInfo:dic[@"code"]];
}

#pragma mark - 充话费、冲流量滚动视图调用方法 - GetPhoneCardsDataDelegate-
-(void)dataWithSelectPage:(NSInteger)page{
    if (page == 1) {
        self.isDefineRequestType = @"tariffe";

        [self requestgetMobileShelfInfosWithPhoneNumber:self.phoneNumber];
    }else{
        self.isDefineRequestType = @"flow";
        [self requestgetTraficShelfInfosWithPhoneNumber:self.phoneNumber];
    }
}

- (void)updateDataFromServerPhoneNumber:(NSString *)phoneNumber numberInfo:(NSString *)numberInfo{
    if ([self.isDefineRequestType isEqualToString:@"tariffe"]) {
        [self requestgetMobileShelfInfosWithPhoneNumber:phoneNumber];
    }else if ([self.isDefineRequestType isEqualToString:@"flow"]) {
        [self requestgetTraficShelfInfosWithPhoneNumber:phoneNumber];
    }else {
        [HUD showMessage:@"数据错误，请重新进入"];
    }
    self.phoneNumber = phoneNumber;
    self.phoneName = numberInfo;
}

#pragma mark - 充值TextField回调方法
//修改空格，变为正常手机号
- (NSString *)phoneNumberReplace:(NSString *)number {
    number = [number stringByReplacingOccurrencesOfString:@" " withString:@""];
    return number;
}

-(void)phoneCardsNumberView:(BKPhone_NumberView *)phoneNumberView textFieldShouldBeginEditing:(UITextField *)textField {
    [self loadPerson];
    //头像变为X；
   [self textFieldConstraints:-17 textField:textField view:phoneNumberView];
    self.phoneNumber = [self phoneNumberReplace:textField.text];
    [self phoneCardsNumberView:phoneNumberView withTextField:textField isEndEditing:@"beginEditing"];
}

- (void)phoneCardsNumberView:(BKPhone_NumberView *)phoneNumberView textFieldShouldEndEditing:(UITextField *)textField {
    self.phoneNumber = [self phoneNumberReplace:textField.text];
    [self phoneCardsNumberView:phoneNumberView withTextField:textField isEndEditing:@"endEditing"];
}

- (void)phoneCardsNumberView:(BKPhone_NumberView *)phoneNumberView textValueChanged:(UITextField *)textField {
    self.phoneNumber = [self phoneNumberReplace:textField.text];
    //头像变为X；
    [self textFieldConstraints:-17 textField:textField view:phoneNumberView];
    [self phoneCardsNumberView:phoneNumberView withTextField:textField isEndEditing:@"valueChanged"];
}

- (void)textFieldConstraints:(NSInteger)integer textField:(UITextField *)textField view:(BKPhone_NumberView *)phoneNumberView {
    [textField mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(phoneNumberView.mas_top).offset(20);
        make.left.mas_equalTo(phoneNumberView.mas_left).offset(17);
        make.right.mas_equalTo(phoneNumberView.mas_right).offset(integer);
        make.bottom.mas_equalTo(phoneNumberView.mas_bottom).offset(-32);
    }];
}

- (void)phoneCardsNumberView:(BKPhone_NumberView *)phoneNumberView withTextField:(UITextField *)textField isEndEditing:(NSString *)isEditing{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *tempPhoneNumber = [textField.text copy];
        tempPhoneNumber = [self phoneNumberReplace:tempPhoneNumber];
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([tempPhoneNumber isEqualToString:@""] ) {
                self.numberView.QCellCoreLabel.text = nil;
                if (self.mainView.isSuccessFlow) {
                    self.mainView.isSuccessFlow = NO;
                    [self.mainView.flowCollectionView reloadData];
                }
                if (self.mainView.isSuccessTariffe) {
                    self.mainView.isSuccessTariffe = NO;
                    [self.mainView.tariffeCollectionView reloadData];
                }
                
            }
            if (tempPhoneNumber.length > 0 && ![isEditing isEqual:@"endEditing"]) {
                
                if (!phoneNumberView.contactImageView.hidden) {
                    phoneNumberView.contactImageView.hidden = YES;
                }
            }else {
                if (phoneNumberView.contactImageView.hidden) {
                    phoneNumberView.contactImageView.hidden = NO;
                    [self textFieldConstraints:-49 textField:textField view:phoneNumberView];
                }
            }
        });
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //是否创建查询TableView；
            //            if (self.recordsNumberArray.count > 0 && tempPhoneNumber.length == 0  && ![isEditing isEqual:@"endEditing"]) {//展示充值记录，最近三次；
            
            
            if (_person.phones.count > 0 && tempPhoneNumber.length == 0  && ![isEditing isEqual:@"endEditing"]) {//展示充值记录，最近三次；
                [self.filterMuArray removeAllObjects];
                self.filterMuArray = [self.recordsNumberArray mutableCopy];
                
                [self initFilterTableView];
                self.filterTableView.hidden = NO;
                [self.filterTableView reloadData];
                
            }else if (tempPhoneNumber.length < 4) {
                self.filterTableView.hidden = YES;
            }else if (tempPhoneNumber.length >= 4 && tempPhoneNumber.length < 11  && ![isEditing isEqual:@"endEditing"]){  //通讯录中查找；
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    self.filterMuArray = [self.addressBookMuArray mutableCopy];
                    [self.tempFilterArray removeAllObjects];
                    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"phoneNumber BEGINSWITH %@",tempPhoneNumber];
                    self.tempFilterArray = [[self.filterMuArray filteredArrayUsingPredicate:predicate] mutableCopy];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (self.tempFilterArray.count == 0) {
                            self.filterTableView.hidden = YES;
                        }else {
                            
                        }
                    });
                });
            }else if (tempPhoneNumber.length == 11) {
                self.filterTableView.hidden = YES;
                self.filterMuArray = [self.addressBookMuArray mutableCopy];
                [self.tempFilterArray removeAllObjects];
                NSPredicate *predicate = [NSPredicate predicateWithFormat:@"phoneNumber BEGINSWITH %@",tempPhoneNumber];
                NSMutableArray *array = [[self.filterMuArray filteredArrayUsingPredicate:predicate] mutableCopy];
                if (array.count > 0) {
                    AddressBookPerson *addressBookPerson = array[0];
                    self.phoneName = addressBookPerson.name;
                }
            }
            // }
            if ([isEditing isEqual:@"endEditing"]) { //结束输入
                self.filterTableView.hidden = YES;
                
                if (tempPhoneNumber.length < 11 && tempPhoneNumber.length != 0) {  //手机号格式错误
                    [self upDateNumberInfoLabel:@"错误" isError:YES];
                }else if (tempPhoneNumber.length == 0) {  //未输入手机号，清空详情区
                    [self upDateNumberInfoLabel:@"" isError:YES];
                }
                if (tempPhoneNumber.length == 11) {
                    if ([self.isDefineRequestType isEqualToString:@"tariffe"]) {
                        self.phoneNumber = [NSString stringWithFormat:@"%@",tempPhoneNumber];
                        [self requestgetMobileShelfInfosWithPhoneNumber:tempPhoneNumber];
                    }else if ([self.isDefineRequestType isEqualToString:@"flow"]) {
                        self.phoneNumber = [NSString stringWithFormat:@"%@",tempPhoneNumber];
                        [self requestgetTraficShelfInfosWithPhoneNumber:tempPhoneNumber];
                    }else {
                        self.phoneNumber = @"";
                    }
                }
            }
            if (tempPhoneNumber.length > 11) {
                
                textField.text = [self.numberView formattingPhoneNumber:[tempPhoneNumber substringToIndex:11]];
            }
            if (tempPhoneNumber.length != 11) {
                if (self.mainView.isSuccessFlow) {
                    self.mainView.isSuccessFlow = NO;
                    [self.mainView.flowCollectionView reloadData];
                }
                if (self.mainView.isSuccessTariffe) {
                    self.mainView.isSuccessTariffe = NO;
                    [self.mainView.tariffeCollectionView reloadData];
                }
            }
            
            if ([isEditing isEqualToString:@"valueChanged"]) {
                if (tempPhoneNumber.length >= 11) {
                    [self.view endEditing:YES];
                }else {
                    //输入进行时，清空提示信息；
                    phoneNumberView.QCellCoreLabel.text = nil;
                    self.phoneName = @"";
                    self.phoneNumber = @"";
                }
            }
        });
    });
}

#pragma mark - 键盘完成取消的回调方法
- (void)finishKeyBoardAction:(UIButton *)sender{
    [self.view endEditing:YES];
    
}

- (void)cancleKeyBoardAction:(UIButton *)sender{
    if (self.lastTrueNumber.length == 11) {
        self.numberView.phoneTextField.text = [self.numberView formattingPhoneNumber:self.lastTrueNumber];
        self.numberView.QCellCoreLabel.text = self.phoneInfo;
    }
    [self.view endEditing:YES];
}




#pragma mark ---展示最近三次充值记录的tableView代理方法-----
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _person.phones.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BKFilterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    [cell getFilterInfoFromDictionary:[_person.phones objectAtIndex:indexPath.row]];
    cell.userInteractionEnabled = YES;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BKFilterTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    self.numberView.phoneTextField.text = [cell.phoneNumber.text copy];
    self.numberView.QCellCoreLabel.text = [cell.phoneInfo.text copy];
    if ([self.isDefineRequestType isEqualToString:@"tariffe"]) {
        [self requestgetMobileShelfInfosWithPhoneNumber:cell.phoneNumber.text];
    } else if ([self.isDefineRequestType isEqualToString:@"flow"]) {
        [self requestgetTraficShelfInfosWithPhoneNumber:cell.phoneNumber.text];
    }
    self.phoneNumber = [self phoneNumberReplace:cell.phoneNumber.text];
    self.phoneName = [cell.phoneInfo.text copy];
    [self.view endEditing:YES];
}

//后台返回信息检测
- (void)mobileNameFromData:(NSString *)provinceName {
    if (provinceName == nil || provinceName.length == 0) {
        self.numberView.QCellCoreLabel.textColor = RGBACOLOR(242, 38, 19, 1);
        self.numberView.QCellCoreLabel.text = @"运营商系统维护中，请稍后重试";
        self.phoneInfo = @"";
    }else {
        self.mobileName = [NSString stringWithFormat:@" (%@)",provinceName];
        [self upDateNumberInfoLabel:@"正常" isError:NO];
    }
}

//手机号信息错误展示方法
- (BOOL)phoneNumberIsErrorWithNumber:(NSString *)phone_NO isFlow:(BOOL)isFlow{
    self.numberView.QCellCoreLabel.textColor = RGB(152, 152, 152);
    
    if ([self isValidateMobile:phone_NO]) {
        self.numberView.QCellCoreLabel.textColor = RGB(242, 38, 19);
        if (phone_NO.length == 0) {
            self.numberView.QCellCoreLabel.text = nil;
        }else {
            self.numberView.QCellCoreLabel.text = @"手机号格式错误";
        }
        if (phone_NO.length != 11) {
           [self.numberView.phoneTextField becomeFirstResponder];
        }
        [self noNetworkCreatDataInfo:^(id obj, NSError *error) {
            if (isFlow) {
                self.mainView.isSuccessFlow = NO;
                self.mainView.phoneCardsFlowList = obj;
                [self.mainView.flowCollectionView reloadData];
            } else {
                self.mainView.isSuccessTariffe = NO;
                self.mainView.phoneCardsTariffeList = obj;
                [self.mainView.tariffeCollectionView reloadData];
            }
        } isFlow:isFlow];
        return NO;
    }
    return YES;
}

- (void)upDateNumberInfoLabel:(NSString *)infoStr isError:(BOOL)isError{
    self.numberView.QCellCoreLabel.textColor = RGBACOLOR(152, 152, 152, 1);
    if (infoStr == nil || [infoStr isEqualToString:@""]) {
        self.numberView.QCellCoreLabel.text = @"";
    }else if (isError){
        self.numberView.QCellCoreLabel.textColor = RGBACOLOR(242, 38, 19, 1);
        self.numberView.QCellCoreLabel.text = @"手机号格式错误";
        
    }else{
        if ([self.phoneNumber isEqualToString:self.registerNumber]) {
            self.phoneName = @"账户绑定号码";
        }
        if (self.phoneName.length > 0 && self.mobileName.length > 0) {
            self.phoneInfo = [self.phoneName stringByAppendingString:self.mobileName];
        }else if (self.mobileName.length > 0){
            self.phoneInfo = [NSString stringWithFormat:@"不在通讯录%@",self.mobileName];
        }else if (self.phoneName.length > 0) {
            self.phoneInfo = self.phoneName;
        }
        self.numberView.QCellCoreLabel.text = self.phoneInfo;
    }
}

/*手机号码验证 MODIFIED BY HELENSONG*/
-(BOOL) isValidateMobile:(NSString *)mobile {
    //^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$
    if (mobile == nil || mobile.length == 0) {
        return YES;
    }
    NSString *patternCellphone =  @"^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$";
    
    NSRegularExpression *regexCellphone = [NSRegularExpression regularExpressionWithPattern:patternCellphone options:0 error:nil];
    
    NSTextCheckingResult *isMatchCellphone = [regexCellphone firstMatchInString:mobile options:0 range:NSMakeRange(0, [mobile length])];
    return !isMatchCellphone;
}

#pragma mark - 点击CollectionView弹出付款界面
- (void)collectionView:(UICollectionView *)collectionView transInfoWithIndexPath:(NSIndexPath *)indexPath {
    [HUD showProgress:nil];
    [self.payInfo setObject:[self phoneNumberReplace:self.phoneNumber] forKey:@"accountNo"];
    if (collectionView.tag == 1888) {
        [self.payInfo setObject:@"2" forKey:@"chargeType"];
        ShelfInfos *shelfinfos = self.mainView.phoneCardsFlowList.shelfInfos[indexPath.item];
        [self.payInfo setObject:shelfinfos.facePrice forKey:@"facePrice"];
        [self.payInfo setObject:shelfinfos.salePrice forKey:@"salePrice"];
    } else if (collectionView.tag == 1889) {
        [self.payInfo setObject:@"1" forKey:@"chargeType"];
        ShelfInfos *shelfinfos = self.mainView.phoneCardsTariffeList.shelfInfos[indexPath.item];
        [self.payInfo setObject:shelfinfos.facePrice forKey:@"facePrice"];
        [self.payInfo setObject:shelfinfos.salePrice forKey:@"salePrice"];
    }
    [self.view endEditing:YES];
    [self transStrWithPayInfo:self.payInfo collectionView:collectionView transInfoWithIndexPath:indexPath];
}

- (void)transStrWithPayInfo:(NSMutableDictionary *)payInfo collectionView:(UICollectionView *)collectionView transInfoWithIndexPath:(NSIndexPath *)indexPath{
    [BKMainCommon phonePayOrder:payInfo callback:^(id obj, NSError *error) {
        if (obj != nil) {
            NSString *orderString = obj[@"orderNo"];
            [BKMainCommon getPhonePayOrderAlipayInfoWithOrderNo:orderString callback:^(id obj, NSError *error) {
                if (obj != nil) {
                    
                    self.alipayInfo = [[OrderAlipayInfo alloc] init];
                    self.alipayInfo = obj;
                    self.payView.delegate = self;
                    [self.payView getOrderAlipayInfo:self.alipayInfo];
                    [HUD dismiss];
                }
                    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
                    cell.backgroundColor = [UIColor whiteColor];
            }];
        } else {
            UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
            cell.backgroundColor = [UIColor whiteColor];
        }
    }];
}

- (void)clickPayButton:(UIButton *)sender {
    [_payView removeFromSuperview];
    _payView = nil;
    if (sender.tag == 0) {
        if ([[self.alipayInfo.pay_way_info objectAtIndex:0][@"pay_way"] hasPrefix:@"微信"]) {
            [self transPayInfoToWeiXin:[self.alipayInfo.pay_way_info objectAtIndex:0][@"pay_info"]];
        }else {
            [self transPayOrder_no:[self.alipayInfo.pay_way_info objectAtIndex:0][@"pay_info"]];
        }
    }else if (sender.tag == 1) {
        if ([[self.alipayInfo.pay_way_info objectAtIndex:1][@"pay_way"] hasPrefix:@"微信"]) {
            [self transPayInfoToWeiXin:[self.alipayInfo.pay_way_info objectAtIndex:1][@"pay_info"]];
        }else {
            [self transPayOrder_no:[self.alipayInfo.pay_way_info objectAtIndex:1][@"pay_info"]];
        }
    }
}

- (void)clickCancelButton {
    [UIView animateWithDuration:0.1 animations:^{
        self.payView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = self.view.bounds;
            frame.size.height = ScreenHeight;
            frame.origin.y = ScreenHeight;
            self.payView.frame = frame;
        } completion:^(BOOL finished) {
            [self.payView removeFromSuperview];
            _payView = nil;
        }];
    }];
}

//支付宝支付回调
- (void)ODWAliManagerDidRecvPayResult:(NSDictionary *)resultDic {
    BKPhonePaySkipVC *resultVC = [[BKPhonePaySkipVC alloc] init];
    resultVC.hidesBottomBarWhenPushed = YES;
    if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {//支付成功
        resultVC.isPaySuccess = YES;
        resultVC.orderAlipayInfor = self.alipayInfo;
        [self savePhoneNumber];
    
    }else{
        resultVC.isPaySuccess = NO;
    }
    [self.navigationController pushViewController:resultVC animated:YES];
}

- (void)savePhoneNumber {
    
    NSString *idStr = [NSString stringWithFormat:@"userId = '%@'",[BKMainCommon getUserId]];
    RLMResults *personResults = [[CacheData shareInstance]search:[Person class] predicate:idStr];
    //此账号有充值记录
    if (personResults.count!= 0) {
                //是否是新的手机号
        if ([self judgeNumberIsNew]) {
            
        }else{
            NSString *searchStr = [NSString stringWithFormat:@"userId = '%@' and phoneNumber = '%@'",[BKMainCommon getUserId],self.phoneNumber];
            RLMResults *infoResults = [[CacheData shareInstance]search:[BKPhoneContactInfo class] predicate:searchStr];
            NSLog(@"%@",infoResults);
            [[CacheData shareInstance] deleteObject:infoResults.firstObject];
        }
        if (_person.phones.count >3) {
            [[CacheData shareInstance] deleteObject:_person.phones.lastObject];
        }
        [_person.realm beginWriteTransaction];
        BKPhoneContactInfo *info = [[BKPhoneContactInfo alloc]init];
        info.phoneNumber = self.phoneNumber;
        info.phoneName = self.phoneName;
        info.localCreateDate = [NSDate date];
        info.userId = [BKMainCommon getUserId];
        [_person.phones addObject:info];
        [_person.realm commitWriteTransaction];

        
    }else{
        //此账号无充值记录
        BKPhoneContactInfo *info = [[BKPhoneContactInfo alloc]init];
        info.phoneNumber = self.phoneNumber;
        info.phoneName = self.phoneName;
        info.localCreateDate = [NSDate date];
        info.userId = [BKMainCommon getUserId];
        Person *person = [[Person alloc]init];
        person.userId = [BKMainCommon getUserId];
        person.localCreateDate = [NSDate date];
        [person.phones addObject:info];
        [[CacheData shareInstance] addOrUpdateObject:person];
    }
}
//微信支付 回调
- (void)managerDidRecvPayResponse:(PayResp *)response {
    BKPhonePaySkipVC *resultVC = [[BKPhonePaySkipVC alloc] init];
    resultVC.hidesBottomBarWhenPushed = YES;
    if (response.errCode == 0) {//支付成功
        resultVC.isPaySuccess = YES;
        resultVC.orderAlipayInfor = self.alipayInfo;
        [self savePhoneNumber];
    } else {
        resultVC.isPaySuccess = NO;
    }
    [self.navigationController pushViewController:resultVC animated:YES];
}

//微信支付
- (void)transPayInfoToWeiXin:(NSString *)pay_info {
    if (![WXApi isWXAppInstalled]) {
        [HUD showMessage:@"您还没有安装微信客户端"];
    }
    NSDictionary *payInfoDic = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:[pay_info UTF8String] length:pay_info.length] options:NSJSONReadingMutableLeaves error:nil];
    PayReq *req = [[PayReq alloc] init];
    req.nonceStr = payInfoDic[@"noncestr"];
    req.package = payInfoDic[@"package"];
    req.partnerId = payInfoDic[@"partnerid"];
    req.prepayId = payInfoDic[@"prepayid"];
    req.sign = payInfoDic[@"sign"];
    req.timeStamp = (UInt32)[payInfoDic[@"timestamp"] intValue];
    [WXApi registerApp:@"wx2c7367321c4ecab5"];
    //调微信支付
    [WXApiManager sharedManager].delegate = self;
    [WXApi sendReq:req];
}

//支付宝支付；
- (void)transPayOrder_no:(NSString *)pay_info {
    [BKODAliManager manager].delegate = self;
    [[BKODAliManager manager] payRequestOrderString:pay_info];
}


- (BOOL)judgeNumberIsNew {
    
    for (BKPhoneContactInfo *info in _person.phones) {
        NSLog(@"%@",_person.phones);
        if ([info.phoneNumber isEqualToString:self.phoneNumber]) {
            return NO;
        }
    }
    return YES;
}

- (void)noNetworkCreatDataInfo:(BKPhonePayCallback)callback isFlow:(BOOL)isFlow {
    BKPhoneCardsList *phoneCardsList = [[BKPhoneCardsList alloc] init];
    phoneCardsList.shelfInfos = [NSMutableArray array];
    if (isFlow) {
        for (int i = 1; i < 7; i++) {
            ShelfInfos *shelfInfos = [[ShelfInfos alloc] init];
            if (i < 4) {
                shelfInfos.facePrice = [NSString stringWithFormat:@"%dM",i * 10];
            }else if (i == 4) {
                shelfInfos.facePrice = [NSString stringWithFormat:@"100M"];
            }else if (i == 5) {
                shelfInfos.facePrice = [NSString stringWithFormat:@"500M"];
            }else {
                shelfInfos.facePrice = [NSString stringWithFormat:@"1024M"];
            }
            
            [phoneCardsList.shelfInfos addObject:shelfInfos];
        }
    }else {
        for (int i = 1; i < 7; i++) {
            ShelfInfos *shelfInfos = [[ShelfInfos alloc] init];
            if (i < 4) {
                shelfInfos.facePrice = [NSString stringWithFormat:@"%d元",i * 10];
            }else if (i == 4) {
                shelfInfos.facePrice = [NSString stringWithFormat:@"%d元",50];
            }else if (i == 5) {
                shelfInfos.facePrice = [NSString stringWithFormat:@"100元"];
            }else {
                shelfInfos.facePrice = [NSString stringWithFormat:@"200元"];
            }
            
            [phoneCardsList.shelfInfos addObject:shelfInfos];
        }
    }
    callback(phoneCardsList,nil);
}

- (UIWindow *)lastWindow {
    return [UIApplication sharedApplication].keyWindow;
}

#pragma mark ----------AddContactPeopleDelagate-----------------
-(void)addContactPerson:(BKPhone_NumberView *)view chooseContactPeople:(Complete)complete{
    //实例化
    ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc] init];
        [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:254/255.f green:254/255.f blue:254/255.f alpha:1.0]];
    [[UINavigationBar appearance] setTintColor:RGB(3, 181, 152)];
    
    [peoplePicker.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor],
                                                         NSFontAttributeName:[UIFont boldSystemFontOfSize:20]
                                                         }];
    //设置代理
    peoplePicker.peoplePickerDelegate = self;
    if(IOS_VERSION >= 8.0f){
        peoplePicker.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];
    }
    
    [self  presentViewController:peoplePicker animated:YES completion:nil];
    self.com = complete;
}

#pragma mark ----peoplePickerNavigationController代理实现----
//点击联系人--->返回联系人信息
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person NS_DEPRECATED_IOS(2_0, 8_0){
    self.com(person,@"");
    [self dismissViewControllerAnimated:YES completion:nil];
    return YES;
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person{
    self.com(person,@"");
    [self dismissViewControllerAnimated:YES completion:nil];
}
//ios8
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
    if (index >= 0) {
        NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
        if ([phoneNO hasPrefix:@"+"]) {
            phoneNO = [phoneNO substringFromIndex:3];
        }
        phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
        
        self.com(person,phoneNO);
    }else {
        self.com(person,@"");
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{
    return NO;
}

- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(nullable ABRecordRef)person{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//获取通讯录；
- (void)loadPerson {
    ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);

    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error){
            if (granted) {
                CFErrorRef *error1 = NULL;
                ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error1);
                [self copyAddressBook:addressBook];
            }
        });
    }
    else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){

        CFErrorRef *error = NULL;
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
        [self copyAddressBook:addressBook];
    }
    else {
        dispatch_async(dispatch_get_main_queue(), ^{

        });
    }
}

- (void)copyAddressBook:(ABAddressBookRef)addressBook {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        [self.addressBookMuArray removeAllObjects];
        CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
        CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);

        for ( int i = 0; i < numberOfPeople; i++){

            ABRecordRef person = CFArrayGetValueAtIndex(people, i);
            //读取电话多值
            ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);

            for (int k = 0; k<ABMultiValueGetCount(phone); k++) {

                AddressBookPerson *addressBookPerson = [[AddressBookPerson alloc] init];
                //获取該Label下的电话值
                NSString * personPhone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);
                NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
                NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
                if ([personPhone hasPrefix:@"+"]) {
                    personPhone = [personPhone substringFromIndex:3];
                }
                NSString *phoneNumber;
                NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$€^•'@#$%^&*()_+'\"- "];
                phoneNumber = [[personPhone componentsSeparatedByCharactersInSet:set]componentsJoinedByString:@""];
                NSString *name;
                if (firstName) {
                    name = firstName;
                    if (lastName) {
                        name = [lastName stringByAppendingString:firstName];
                    }
                }else if (lastName) {
                    name = lastName;
                }else {
                    name = @"";
                }
                [addressBookPerson setName:[NSString stringWithFormat:@"%@",name]];
                [addressBookPerson setPhoneNumber:phoneNumber];
                [self.addressBookMuArray addObject:addressBookPerson];
            }
        }
    });
}

#pragma mark --- 懒加载

- (NSMutableArray *)tempFilterArray {
    if (_tempFilterArray == nil) {
        _tempFilterArray = [NSMutableArray array];
    }
    return _tempFilterArray;
}

- (NSMutableArray *)recordsNumberArray {
    if (_recordsNumberArray == nil) {
        _recordsNumberArray = [NSMutableArray array];
    }
    return _recordsNumberArray;
}

- (NSMutableArray *)filterMuArray {
    if (_filterMuArray == nil) {
        _filterMuArray = [NSMutableArray array];
    }
   return _filterMuArray;
}

- (NSMutableArray *)addressBookMuArray {
    if (_addressBookMuArray == nil) {
        _addressBookMuArray = [NSMutableArray array];
    }
    return _addressBookMuArray;
}

- (NSMutableDictionary *)payInfo {
    if (!_payInfo) {
        _payInfo = [NSMutableDictionary dictionary];
    }
    return _payInfo;
}

- (void)initFilterTableView {
    
    self.filterTableView.delegate = self;
    self.filterTableView.dataSource = self;
    [self.filterTableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
        make.bottom.mas_equalTo(self.view.mas_bottom);
        make.top.mas_equalTo(self.numberView.mas_bottom);
    }];
}

- (UITableView *)filterTableView {
    if (!_filterTableView) {
        _filterTableView = [[UITableView alloc] init];
        _filterTableView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
        _filterTableView.bounces = NO;
        _filterTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_filterTableView registerClass:[BKFilterTableViewCell class] forCellReuseIdentifier:@"cell"];
        [self.view addSubview:_filterTableView];
    }
    return _filterTableView;
}

- (BKPhonePayView *)payView {
    if (!_payView) {
        CGRect frame = self.view.bounds;
        frame.size.height = ScreenHeight;
        _payView = [[BKPhonePayView alloc] initWithFrame:frame];
        [[self lastWindow] addSubview:_payView];
        [[self lastWindow] bringSubviewToFront:_payView];
    }
    return _payView;
}

-(BKPhone_Header *)headerView{
    if (!_headerView) {
        _headerView = [[BKPhone_Header alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, 70)];
    }
    return _headerView;
}

-(BKPhone_NumberView *)numberView{
    if (!_numberView) {
        _numberView = [[BKPhone_NumberView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, 100)];
        _numberView.delegate = self;
    }
    return _numberView;
}

-(BKPhone_MainView *)mainView{
    if (!_mainView) {
        _mainView = [[BKPhone_MainView alloc]init];
        _mainView.delegate = self;
        [self.view addSubview:_mainView];
        _phoneCardsRecordButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_phoneCardsRecordButton setTitle:@"充值记录" forState:UIControlStateNormal];
        [_phoneCardsRecordButton setTitleColor:RGBACOLOR(181, 181, 181, 1) forState:UIControlStateNormal];
        _phoneCardsRecordButton.titleLabel.font = [Common systemFontOfSize:14];
        [self.view addSubview:_phoneCardsRecordButton];
        [_phoneCardsRecordButton addTarget:self action:@selector(phoneCardsRecordAction) forControlEvents:UIControlEventTouchUpInside];
        [_phoneCardsRecordButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.view.mas_centerX);
            make.bottom.mas_equalTo(self.view.mas_bottom).offset(-14);
            make.width.mas_equalTo(self.view.mas_width).multipliedBy(0.5);
            make.height.mas_equalTo(36);
        }];
    }
    return _mainView;
}

- (void)phoneCardsRecordAction{
    self.hidesBottomBarWhenPushed = YES;
    BKPhoneCardsRecordViewController *recordVC = [[BKPhoneCardsRecordViewController alloc]init];
    [self.navigationController pushViewController:recordVC animated:YES];
}

- (void)clickGoodsInfoType:(NSInteger)type goodsInfo:(NSString *)goodsInfo{
    switch (type) {
        case 1:
            [self pushClassifyVC:goodsInfo];
            break;
            
        case 2:
            [self pushGoodsVC:goodsInfo];
            break;
            
        case 3:
            [self pushGoodsVC:goodsInfo];
            break;
            
        case 4:
            [self pushH5VC:goodsInfo];
            break;
            
        case 5:
            [self pushAllClassifyVC:goodsInfo];
            break;
            
        default:
            break;
    }
}

- (void)pushGoodsVC:(NSString *)goodId {
    UIViewController *vc = [[Mediator sharedInstance] BKGD_goodsDetailViewController:goodId saleTypes:@""];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)pushH5VC:(NSString *)url {
    BKIntegralBookViewController *integralBookVC = [[BKIntegralBookViewController alloc]init];
    integralBookVC.urlString = url;
    integralBookVC.view.backgroundColor = [UIColor whiteColor];
    [self .navigationController pushViewController:integralBookVC animated:YES];
}
- (void)pushClassifyVC:(NSString *)classify {
    UIViewController *vc = [[Mediator sharedInstance] HomeIntorecordPushInformationWithFilterTerms:@"-1" categotyId:classify channelType:@"" orderKey:@"" currentPage:0 keyWord:@"" order:@""];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)pushAllClassifyVC:(NSString *)allClassify {
    UIViewController *vc = [[Mediator sharedInstance] HomeIntorecordPushInformationWithFilterTerms:@"-1" categotyId:allClassify channelType:@"" orderKey:@"" currentPage:0 keyWord:@"" order:@""];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)explainQuestion {
    BKIntegralBookViewController *integralBookVC = [[BKIntegralBookViewController alloc]init];
    integralBookVC.urlString = @"http://cdn.bestkeep.cn/ui/mobile/html/phonePrepaidHelp.html";
    [self.navigationController pushViewController:integralBookVC animated:YES];
    integralBookVC.view.backgroundColor = ThemeBackgroundColor;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
